package com.zcurd.common.plugin;


import java.util.Enumeration;
import java.util.List;
import java.util.Properties;

import org.quartz.Scheduler;
import org.quartz.impl.StdSchedulerFactory;

import com.jfinal.kit.PropKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.IPlugin;
import com.zcurd.common.plugin.job.QuartzCronJob;
import com.zcurd.common.plugin.job.QuartzJob;
import com.zcurd.common.plugin.job.QuartzOnceJob;
import com.zcurd.model.SysJob;
/**
 * @author xpg.
 */
public class QuartzPlugin implements IPlugin {
  private Log logger = Log.getLog(QuartzPlugin.class); 
  public static String dsName = "main";
  public static boolean dsAlone = false;
  /**
   * 默认配置文件*
   */
  private String config = "quartz/quartz.properties";
  private String jobs = "quartz/jobs.properties";

  public QuartzPlugin() {

  }

  @SuppressWarnings("static-access")
public QuartzPlugin(String dsName) {
    this.dsName = dsName;
  }


  public boolean start() {
    try {
     
      //加载配置文件
      Properties properties = PropKit.use(config).getProperties();
      //实例化
      QuartzKit.setSchedulerFactory(new StdSchedulerFactory(properties));
      //获取Scheduler
      Scheduler sched = QuartzKit.getSchedulerFactory().getScheduler();
      
      sched.start();
      /**
      if(properties.getProperty("tableJobs").equals("true")){
    	//数据库表中的任务
    	  List<SysJob> Job =SysJob.me.getJobList();
          startSysJobs(Job);
      }
      else {
    	  //属性文件中的任务
    	  //startPropertiesJobs();
          //数据库中的任务  
      } 
      **/
      
      return true;
    } catch (Exception e) {
      throw new RuntimeException("Can't start quartz plugin.", e);
    }
  }


  public boolean stop() {
    try {
      QuartzKit.getSchedulerFactory().getScheduler().shutdown();
      QuartzKit.setSchedulerFactory(null);
      return true;
    } catch (Exception e) {
      throw new RuntimeException("Can't stop quartz plugin.", e);
    }
  }

//从配置文件启动定时任务
  @SuppressWarnings({ "unchecked", "rawtypes" })
public void startPropertiesJobs() {
	
	  //加载配置文件
      Properties properties = PropKit.use(jobs).getProperties();
      Enumeration<?> enums = properties.keys();
      while (enums.hasMoreElements()) {
        String key = enums.nextElement() + "";
        if (!key.startsWith("job")) {
          continue;
        }

        String[] keyArr = key.split("\\.");
        String jobClassKey = key.replace(keyArr[2], "class");
        String idKey = key.replace(keyArr[2], "id");
        String groupKey = key.replace(keyArr[2], "group");
        String cronKey = key.replace(keyArr[2], "cron");
        String enable = key.replace(keyArr[2], "enable");

        //判断任务是否启用
        if (!Boolean.valueOf(properties.getProperty(enable))) {
          continue;
        }

        Integer id = Integer.parseInt(properties.getProperty(idKey));
        String group = properties.getProperty(groupKey);

        QuartzKey quartzKey = new QuartzKey(id, keyArr[1], group == null ? keyArr[1] : group);

        QuartzJob quartzJob = QuartzKit.getJob(quartzKey);
        if (quartzJob != null) {
          logger.info("This  job  has started," + quartzKey);
          continue;
        }

        String jobCron = properties.getProperty(cronKey);
        String jobClassName = properties.getProperty(jobClassKey);
        Class clazz;
        try {
          clazz = Class.forName(jobClassName);
        } catch (ClassNotFoundException e) {
          throw new RuntimeException(e);
        }
        //启动Cron任务
        new QuartzCronJob(quartzKey, jobCron, clazz).start();
      }
    
  }
  
  
  /**
   * 从数据库表启动定时任务
   */
  
  @SuppressWarnings({ "unchecked", "rawtypes" })
public void startSysJobs(List<SysJob> sysjobs) {
  	
  	  if(!sysjobs.isEmpty())
	   for(SysJob sysjob:sysjobs)
	   {	  
                        
          QuartzKey quartzKey = new QuartzKey(sysjob.getInt("id"),sysjob.getStr("job_name"),sysjob.getStr("job_group"));
          QuartzJob quartzJob = QuartzKit.getJob(quartzKey);
          if (quartzJob != null) {
            logger.info("This  job  has started," + quartzKey);
            continue;
          }         
         
          Class clazz;
          try {
            clazz = Class.forName(sysjob.getStr("job_class"));
          } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
          }
          if(sysjob.getInt("job_type")==1){
        	//启动任务,根据Job_cron字段规则启动任务
              new QuartzCronJob(quartzKey, sysjob.getStr("job_cron"), clazz).start();
          }
          if(sysjob.getInt("job_type")==2){
          	//启动任务,根据start_time字段预定日期启动任务
                new QuartzOnceJob(quartzKey, sysjob.getDate("start_time"), clazz).start();
            }         
            
        }
      
    }
  public String getConfig() {
    return config;
  }

  public void setConfig(String config) {
    this.config = config;
  }

  public static boolean isDsAlone() {
    return dsAlone;
  }

  public static void setDsAlone(boolean dsAlone) {
    QuartzPlugin.dsAlone = dsAlone;
  }

public String getJobs() {
	return jobs;
}

public void setJobs(String jobs) {
	this.jobs = jobs;
}
}